package db_test

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/olivere/elastic/v7"
)

const ES_URL = "http://localhost:9200"

// ElasticSearch结构体
type ElasticSearch struct {
	EsClient *elastic.Client
	EsUrl    string // 连接url
}

type Person struct {
	Name    string `json:"name"`
	Age     int    `json:"age"`
	Married bool   `json:"married"`
}

type Employee struct {
	FirstName string   `json:"first_name"`
	LastName  string   `json:"last_name"`
	Age       int      `json:"age"`
	About     string   `json:"about"`
	Interests []string `json:"interests"`
}

// 创建结构体实例
func NewElasticSearchStruct() *ElasticSearch {
	return &ElasticSearch{
		EsUrl: ES_URL,
	}
}

// 初始化es实例
func (e *ElasticSearch) NewElasticSearch() *ElasticSearch {
	elasticsearch := NewElasticSearchStruct()

	errorlog := log.New(os.Stdout, "APP: ", log.LstdFlags)

	var err error
	elasticsearch.EsClient, err = elastic.NewClient(elastic.SetURL(ES_URL), elastic.SetErrorLog(errorlog))
	if err != nil {
		panic(err)
	}
	info, code, err := elasticsearch.EsClient.Ping(ES_URL).Do(context.Background())
	if err != nil {
		panic(err)
	}
	fmt.Printf("Elasticsearch returned with code %d and version %s\n", code, info.Version.Number)

	esversion, err := elasticsearch.EsClient.ElasticsearchVersion(ES_URL)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Elasticsearch version %s\n", esversion)
	return elasticsearch
}
